package gwt.immunology.client.activity;

import gwt.immunology.client.ClientFactory;
import gwt.immunology.client.i18n.ImmunologyI18N;
import gwt.immunology.client.place.AllPatientsPlace;
import gwt.immunology.client.place.SearchPatientsPlace;
import gwt.immunology.client.service.PatientsService;
import gwt.immunology.client.service.PatientsServiceAsync;
import gwt.immunology.client.view.SearchPatientsView;
import gwt.immunology.shared.GenericDto;
import gwt.immunology.shared.ResultSetDto;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import static gwt.immunology.shared.GenericDtoKeys.PATIENTS_COUNT;
import static gwt.immunology.shared.GenericDtoKeys.PATIENTS_SEARCH_RESULT;

public class SearchPatientsActivity extends AbstractActivity implements SearchPatientsView.Presenter {
    private ClientFactory clientFactory;
    private ImmunologyI18N i18n = GWT.create(ImmunologyI18N.class);
    private final PatientsServiceAsync patientsService = GWT.create(PatientsService.class);

    public SearchPatientsActivity(SearchPatientsPlace place, ClientFactory clientFactory) {
    	this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
		SearchPatientsView searchPatientsView = this.clientFactory.getSearchPatientsView();
		searchPatientsView.setPresenter(this);
		panel.setWidget(searchPatientsView.asWidget());
		Window.setTitle(i18n.patientsSearch());
    }

    @Override
    public void findPatients(GenericDto searchCriteria) {
		patientsService.findPatients(searchCriteria, new AsyncCallback<GenericDto>() {
	
		    @Override
		    public void onSuccess(GenericDto searchResult) {
		    	Long patientsCount = searchResult.getLong(PATIENTS_COUNT);
				ResultSetDto patientsSearchResult = searchResult.getResultSetDto(PATIENTS_SEARCH_RESULT);
				goTo(new AllPatientsPlace(patientsSearchResult, patientsCount));
		    }
	
		    @Override
		    public void onFailure(Throwable caught) {
			Window.alert("Failure to find patients");
		    }
		});
    }

    @Override
    public void goTo(Place place) {
    	this.clientFactory.getPlaceController().goTo(place);
    }
}
